local UserCommands = require("usercommands")

local EDanmuType = {
    None = 0,
    Chat = 1,
    SCChat = 2,
    Gift = 3,
    ZuanFen = 4,
    Cmd = 5,
    Tips = 6,
}

local MyDanmuComp = Class(function(self, inst)
    self.inst = inst
    
    self.totaltime = 0
    self.cur = 0
    self.interval = 0.5
    self.msgqueue_withtime = {}--{{time=,msg={time=,type=,content=,extension=}}}
end)

function MyDanmuComp:Start()
    self.inst:StartUpdatingComponent(self)
end

function MyDanmuComp:Stop()
    self.inst:StopUpdatingComponent(self)
end


function MyDanmuComp:OnUpdate(dt)
  
    if not self.inst then
		self:Stop()
		return
	end

    self.totaltime = self.totaltime + dt
    self.cur = self.cur + dt

    if self.cur >= self.interval then
        self:CheckSomething()
        self.cur = 0
    end

    if #self.msgqueue_withtime > 0 then
        for i,v in ipairs(self.msgqueue_withtime) do
            if v.time < self.totaltime then
                self:SaySomething(v.msg)
                table.remove(self.msgqueue_withtime, i)
                break
            end
        end
    end
end

function MyDanmuComp:AddMsgWithTime(ttime, tmsg)
    table.insert(self.msgqueue_withtime, {time=ttime, msg=tmsg})
end 

function MyDanmuComp:SaySomething(msg)
    print("SaySomething", msg.time, msg.type, msg.content, msg.extension)
    if msg.type == EDanmuType.Chat or msg.type == EDanmuType.SCChat then
        c_remote(string.format("c_announce(\"%s\")",msg.content))
    elseif msg.type == EDanmuType.Gift or msg.type == EDanmuType.ZuanFen then
        self.inst.components.talker:Say(msg.content)
        UserCommands.RunTextUserCommand("dance", ThePlayer, false)
        c_remote(string.format("c_announce(\"%s\",0,\"system\")",msg.content))
    elseif msg.type == EDanmuType.Cmd then
        c_remote(msg.content)
    elseif msg.type == EDanmuType.Tips then
        self.inst.components.talker:Say(msg.content, 5)
        c_remote(string.format("c_announce(\"%s\",0,\"system\")",msg.content))
    end
end

function MyDanmuComp:CheckSomething()
    TheSim:QueryServer("http://127.0.0.1:51234",
		function(result, isSuccessful, resultCode)
            --print("result ", result, isSuccessful, resultCode)
			if isSuccessful and resultCode == 200 then
                local res = json.decode(result)
                if res.chatList ~= nil then
                    local count = #res.chatList
                    print("res.chatList count ", count)
                    if count > 0 then
                        local timestamp = os.time() - 1 --当前时间戳必然大于历史消息，取1秒前的时间戳
                        for i, v in ipairs(res.chatList) do
                            if v.time/1000 > timestamp then
                                self:AddMsgWithTime(self.totaltime + v.time/1000 - timestamp, v)
                            end
                        end
                    end
                end
            end
		end,
    "GET")
end

return MyDanmuComp
